import React, { createContext, useContext, useState, useEffect } from 'react';
import api from '../services/api';

const UserContext = createContext();

export const useUser = () => {
  const context = useContext(UserContext);
  if (!context) {
    throw new Error('useUser must be used within a UserProvider');
  }
  return context;
};

export const UserProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(false);

  // 从token中获取用户信息
  const fetchUserInfo = async () => {
    const token = localStorage.getItem('access_token');
    if (!token) {
      setUser(null);
      return;
    }

    setLoading(true);
    try {
      const response = await api.get('/users/me');
      setUser(response.data);
    } catch (error) {
      console.error('获取用户信息失败:', error);
      // 如果token无效，清除本地存储
      if (error.response?.status === 401) {
        localStorage.removeItem('access_token');
        setUser(null);
      }
    } finally {
      setLoading(false);
    }
  };

  // 登录成功后设置用户信息
  const login = async (token) => {
    localStorage.setItem('access_token', token);
    await fetchUserInfo();
  };

  // 登出
  const logout = () => {
    localStorage.removeItem('access_token');
    setUser(null);
  };

  // 检查是否有权限访问某个功能
  const hasPermission = (permission) => {
    if (!user) return false;
    
    const { role } = user;
    
    const permissions = {
      admin: [
        'view_dashboard',
        'manage_users',
        'manage_issues',
        'manage_cases', 
        'manage_resources',
        'view_reports',
        'system_settings',
        'create_issue',
        'edit_issue',
        'delete_issue',
        'approve_case'
      ],
      engineer: [
        'view_dashboard',
        'manage_issues',
        'manage_cases',
        'manage_resources',
        'view_reports',
        'create_issue',
        'edit_issue',
        'approve_case'
      ],
      customer: [
        'view_dashboard',
        'view_issues',
        'view_cases',
        'view_resources',
        'create_issue'
      ]
    };
    
    return permissions[role]?.includes(permission) || false;
  };

  // 获取用户可访问的菜单项
  const getAccessibleMenuItems = () => {
    if (!user) return [];
    
    const allMenuItems = [
      {
        key: '/',
        icon: 'DashboardOutlined',
        label: '仪表板',
        permission: 'view_dashboard'
      },
      {
        key: '/issues',
        icon: 'BugOutlined', 
        label: '问题管理',
        permission: 'manage_issues'
      },
      {
        key: '/cases',
        icon: 'BookOutlined',
        label: '案例库',
        permission: 'manage_cases'
      },
      {
        key: '/resources',
        icon: 'FolderOutlined',
        label: '资源中心',
        permission: 'manage_resources'
      },
      {
        key: '/reports',
        icon: 'BarChartOutlined',
        label: '统计报表',
        permission: 'view_reports'
      },
      {
        key: '/settings',
        icon: 'SettingOutlined',
        label: '系统设置',
        permission: 'system_settings'
      }
    ];
    
    return allMenuItems.filter(item => hasPermission(item.permission));
  };

  useEffect(() => {
    // 组件挂载时检查是否已登录
    const token = localStorage.getItem('access_token');
    if (token) {
      fetchUserInfo();
    }
  }, []);

  const value = {
    user,
    loading,
    login,
    logout,
    hasPermission,
    getAccessibleMenuItems,
    fetchUserInfo
  };

  return (
    <UserContext.Provider value={value}>
      {children}
    </UserContext.Provider>
  );
};

export default UserContext;